package com.fxz.edu.ad.remote;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fxz.edu.ad.entity.PromotionAd;
import com.fxz.edu.ad.entity.PromotionSpace;
import com.fxz.edu.ad.service.IPromotionAdService;
import com.fxz.edu.ad.service.IPromotionSpaceService;
import com.fxz.edu.dto.PromotionAdDto;
import com.fxz.edu.dto.PromotionSpaceDTO;
import com.fxz.edu.remote.AdRemoteService;
import com.fxz.edu.util.ConverUtil;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-08-30 10:37
 */
@AllArgsConstructor
@RestController
@RequestMapping("/ad")
public class AdRemoteServiceImpl implements AdRemoteService {

    private final IPromotionSpaceService promotionSpaceService;

    private final IPromotionAdService promotionAdService;

    /**
     * 获取所有的广告位信息
     *
     * @return
     */
    @Override
    @GetMapping("/space/getAllSpace")
    public List<PromotionSpaceDTO> getAllSpaces() {
        List<PromotionSpace> promotionSpaces = promotionSpaceService.list();
        //属性拷贝
        return ConverUtil.convertList(promotionSpaces, PromotionSpaceDTO.class);
    }

    /**
     * 根据spaceKey获取广告位以及广告信息
     *
     * @param spaceKey
     * @return
     */
    @GetMapping("/getAdBySpaceKey")
    @Override
    public List<PromotionSpaceDTO> getAdBySpaceKey(String[] spaceKey) {
        //通过spaceKey从数据库获取广告位信息
        List<PromotionSpace> spaces = promotionSpaceService.list(new LambdaQueryWrapper<PromotionSpace>().in(ArrayUtil.isNotEmpty(spaceKey), PromotionSpace::getSpaceKey, spaceKey));

        //属性拷贝
        List<PromotionSpaceDTO> promotionSpaceDTOS;
        promotionSpaceDTOS = ConverUtil.convertList(spaces, PromotionSpaceDTO.class);

        //获取广告位对应的广告
        promotionSpaceDTOS = promotionSpaceDTOS.stream().map(item -> {
            List<PromotionAd> ads = promotionAdService.list(new LambdaQueryWrapper<PromotionAd>()
                    .eq(PromotionAd::getSpaceId, item.getId())
                    .eq(PromotionAd::getStatus, 1)
                    .lt(PromotionAd::getStartTime, new Date())
                    .gt(PromotionAd::getEndTime, new Date()));
            List<PromotionAdDto> promotionAdDtos = ConverUtil.convertList(ads, PromotionAdDto.class);
            return item.setAdDtoList(promotionAdDtos);
        }).collect(Collectors.toList());

        return promotionSpaceDTOS;
    }
}
